// Package utils
// @program: bannerstudioblog
// @author: Hyy
// @create: 2022-02-11 22:15
package utils

import (
	"context"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/tencentyun/cos-go-sdk-v5"
	"github.com/tencentyun/cos-go-sdk-v5/debug"
	"io"
	"net/http"
	"net/url"
	"os"
)

func getCos() *cos.Client {
	f, _ := os.OpenFile("./log.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
	u, _ := url.Parse(fmt.Sprintf(
		beego.AppConfig.String("COS_URL_FORMAT"),
		beego.AppConfig.String("COS_BUCKET_NAME"),
		beego.AppConfig.String("COS_APP_ID"),
		beego.AppConfig.String("COS_REGION"),
	))
	b := &cos.BaseURL{BucketURL: u}
	c := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  beego.AppConfig.String("COS_SECRET_ID"),
			SecretKey: beego.AppConfig.String("COS_SECRET_KEY"),
			Transport: &debug.DebugRequestTransport{
				RequestHeader: true,
				// Notice when put a large file and set need the request body, might happend out of memory error.
				RequestBody:    false,
				ResponseHeader: true,
				ResponseBody:   true,
				Writer:         f,
			},
		},
	})
	return c
}

func logStatus(err error) bool {
	if err == nil {
		return true
	}
	if cos.IsNotFoundError(err) {
		// WARN
		logs.Warn("WARN: Resource is not existed")
		return false
	} else if e, ok := cos.IsCOSError(err); ok {
		logs.Warn(fmt.Sprintf("ERROR: Code: %v\n", e.Code))
		logs.Warn(fmt.Sprintf("ERROR: Message: %v\n", e.Message))
		logs.Warn(fmt.Sprintf("ERROR: Resource: %v\n", e.Resource))
		logs.Warn(fmt.Sprintf("ERROR: RequestID: %v\n", e.RequestID))
		return false
		// ERROR
	} else {
		logs.Warn(fmt.Sprintf("ERROR: %v\n", err))
		return false
		// ERROR
	}
}

// Upload
// @Title Upload
// @Description "上传文件"
// @Param filesPath 	string 	"想要上传的文件路径 如：./images.png"
// @return	string 	"图片访问链接"
func Upload(fileName string, file io.Reader) string {
	c := getCos()
	response, err := c.Object.Put(context.Background(), fileName, file, nil)
	logs.Warn(response.Header)
	if logStatus(err) {
		return fmt.Sprintf(
			beego.AppConfig.String("COS_URL_FORMAT")+"/%v",
			beego.AppConfig.String("COS_BUCKET_NAME"),
			beego.AppConfig.String("COS_APP_ID"),
			beego.AppConfig.String("COS_REGION"),
			fileName,
		)
	} else {
		return ""
	}

}

//// DownLoad
//// @Title DownLoad
//// @Description "下载文件"
//// @Param fileName 	string 	"想要下载的文件名 如：xx.png"
//// @Param fileSavePath 	string 	"保存到本地的路径，如：./image"
//// @return	bool "下载是否成功"
//func DownLoad(fileName string, fileSavePath string) bool {
//	c := getCos()
//	_, err := c.Object.GetToFile(context.Background(), fileName, fileSavePath+"/recv_"+fileName, nil)
//	return logStatus(err)
//}

// Delete
// @Title Delete
// @Description "删除文件"
// @Param fileName 	string 	"想要删除的文件名 如：xx.png"
// @return	bool "删除是否成功"
func Delete(fileName string) bool {
	c := getCos()
	_, err := c.Object.Delete(context.Background(), fileName, nil)
	return logStatus(err)
}
